# encoding: utf-8
'''
Created on 2018-8-21
desription:数据库连接助手类， for pgsql
@author: szy
'''

import cx_Oracle
import sys
import time

#sys.path.append('./helper')
from helper import InfoMonConstants
#import InfoMonConstants
import threading
import psycopg2
import psycopg2.pool

class ConnectionHelper:
    conn = None
    _l = None
    def __init__(self,dbName):
        self._l = threading.Lock()
        self.conn = psycopg2.connect(database=InfoMonConstants.DBNAME, user=InfoMonConstants.USER, password=InfoMonConstants.PASSWORD, host=InfoMonConstants.HOST, port=InfoMonConstants.PORT)


    def getConnection(self, dbName):
        myconn = psycopg2.connect(database=dbName, user=InfoMonConstants.USER, password=InfoMonConstants.PASSWORD, host=InfoMonConstants.HOST, port=InfoMonConstants.PORT)
        return myconn

    def getResult(self, myconn, query):
        cursor = myconn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        return result

    # def getCursor(self):
    #     return self.conn.cursor()
    def getValue(self, query):
        self._l.acquire()
        cursor = self.conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        self.conn.commit()
        self._l.release()
        return result

    def getDbName(self):
        sql = "select datname from pg_database where datname not in ('template0', 'template1')"
        cursor = self.conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        return result

    def closeConn(self):
        self.conn.close()


